package abc.filter;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.*;

@Slf4j
@Component
@RefreshScope
@Order(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnExpression("${abc.api.validation-enable:false}")
public class ValidationFilter implements WebFilter, GlobalFilter, Ordered {


    private final ThreadLocal<List<String>> localFilterNames = new ThreadLocal<>() {{ set(new ArrayList<>());}};

    @Autowired
    ValidationHandler validationHandler;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        log.info("Validation WebFilterChain doing......");
        return validationChain(exchange, chain);
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("Validation GatewayFilterChain doing......");
        return validationChain(exchange, chain);
    }

    private Mono<Void> validationChain(ServerWebExchange exchange, Object chain) {
        ServerHttpRequest request = exchange.getRequest();
        if(localFilterNames.get() == null) {
            localFilterNames.set(new ArrayList<>());
        }
        //判断过滤器是否执行
        String requestUrl = String.valueOf(request.getPath());
        if (!localFilterNames.get().contains(requestUrl)) {
            localFilterNames.get().add(requestUrl);

        }
        return validationHandler.filter(exchange, chain);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
